import { ProgressBar, Toast } from 'antd-mobile'
import React, { useEffect, useState } from 'react'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { VipPrivilegeData, GlamourPrivilegeData, GetUserInfo, clearLevelReq } from '../../api/mine'
import NavBar from '../../components/Navbar'
import './index.less'
import appSdk from '../../utils/app_sdk'
import { compareVersions, getVersion, isIOS } from '../../utils/util'
import AmeModal from '../../components/AmeModal'
import { useCountDown } from 'ahooks'

const data = {
  glamour: {
    level: [
      { level: 1, name: '新秀崛起', icon: '' },
      { level: 2, name: '当红小生', icon: '' },
      { level: 3, name: '明日之星', icon: '' },
      { level: 4, name: '一线明星', icon: '' },
      { level: 5, name: '天王巨星', icon: '' }
    ],
    in: '魅力值',
    upIntro: ['收到礼物会增加魅力值', `1${window.baseConfig.coin_name}的礼物=1魅力值`],
    tips: '魅力值代表一个人的受欢迎程度，在聊天室活跃且接受礼物关注等，即可提升魅力值'
  },
  vip: {
    level: [
      { level: 1, name: '默默无闻', icon: '' },
      { level: 2, name: '锋芒毕露', icon: '' },
      { level: 3, name: '闻名一方', icon: '' },
      { level: 4, name: '声名远扬', icon: '' },
      { level: 5, name: '名冠天下', icon: '' }
    ],
    in: '财富等级',
    upIntro: ['赠送礼物会增加VIP值', `1${window.baseConfig.coin_name}的礼物=1VIP值`],
    tips: 'VIP代表一个人的豪气程度，在聊天室活跃且赠送礼物关注等，即可提升VIP成长值'
  }
}

const backgroundLevel = (level) => {
  if (!level || level <= 0) return 0
  if (level <= 12) return 1
  if (level > 12 && level <= 24) return 2
  if (level > 24 && level <= 36) return 3
  if (level > 36 && level <= 48) return 4
  if (level > 48 && level <= 60) return 5
}

const NavTab = ({ navigate, type, onClick }) => {
  return (
    <div className="nav_tab">
      <span className={`${type === 'glamour' ? 'active' : 'un'}`} onClick={() => onClick('glamour')}>
        魅力等级
      </span>
      <span className={`${type === 'vip' ? 'active' : 'un'}`} onClick={() => onClick('vip')}>
        财富等级
      </span>
    </div>
  )
}

function LevelIntroduction() {
  const params = useSearchParams()[0]
  const navigate = useNavigate()
  const [levelData, setLevelData] = useState({
    stageLevel: 0,
    diff: 0,
    exp: 0,
    glamour: 0,
    wealth: 0,
    stage: { 1: [1, 573] },
    reward: []
  })
  const [type, setType] = useState(params.get('type') || 'vip') // vip | glamour
  const [nickname, setNickname] = useState('')
  const [userInfo, setUserInfo] = useState({ headimgurl: '', wealth_level: 0, glamour_level: 0, is_union_member: 0 })

  const onChange = (type) => {
    setType(type)
    navigate(`/level_introduction?type=${type}`)
  }

  const [isNew, setIsNew] = useState(true) // 是否0级
  const getUser = () => {
    // Toast.show({
    //   title: '加载中...',
    //   icon: 'loading'
    // })
    GetUserInfo()
      .then((res) => {
        console.log(res)
        setNickname(res.data.nickname)
        setUserInfo(res.data)
        if (type === 'vip') {
          setIsNew(!res.data.wealth_level)
        }
        if (type === 'glamour') {
          setIsNew(!res.data.glamour_level)
        }
      })
      .finally(() => {
        Toast.clear()
      })
  }

  const getVip = () => {
    VipPrivilegeData().then((res) => {
      setLevelData(res.data)
    })
  }

  const getGlamour = () => {
    GlamourPrivilegeData().then((res) => {
      setLevelData(res.data)
    })
  }

  useEffect(() => {
    getUser()
    if (type === 'vip') {
      getVip()
    } else {
      getGlamour()
    }
  }, [type])

  const [barHeight, setBarHeight] = useState(0)
  useEffect(() => {
    console.log(
      `%c Version = ${getVersion() || '1.0.0'} %c`,
      'background:#41b883 ; padding: 4px; border-radius: 4px;  color: #fff',
      'background:transparent'
    )
    if (compareVersions(getVersion() || '1.0.0', '2.2.0') !== -1) {
      appSdk('setFullScreen', 1)
      if (window?.android && window?.android?.getStatusBarHeight) {
        if (window.android.getStatusBarHeight()) {
          setBarHeight(window.android.getStatusBarHeight() / window.devicePixelRatio)
        }
        console.log('拿到状态栏高度', window.android.getStatusBarHeight(), window.devicePixelRatio)
      } else if (isIOS()) {
        appSdk('getStatusBarHeight', null, (res) => {
          console.log('拿到ios状态栏高度', res, window.devicePixelRatio)
          setBarHeight(res / window.devicePixelRatio)
        })
      }
    }
  }, [])

  const [targetDate, setTargetDate] = useState()
  const [countdown] = useCountDown({
    targetDate
  })
  const [visible, setVisible] = useState(false)

  const clearLevel = () => {
    Toast.show({
      icon: 'loading',
      maskClickable: false
    })
    clearLevelReq({
      type: type === 'vip' ? 1 : 2 // 类型 1：财富 2：魅力
    })
      .then(() => {
        setVisible(false)
        Toast.show({
          content: '清除成功',
          maskClickable: false
        })
        getUser()
        if (type === 'vip') {
          getVip()
        } else {
          getGlamour()
        }
      })
      .catch((err) => {
        console.log('err', err)
        Toast.show({
          content: err.message || '系统错误'
        })
      })
  }

  return (
    <div className="level_introduction_wrap">
      <div
        className={`level_introduction ${type} level_${backgroundLevel((type === 'vip' ? +userInfo.wealth_level : +userInfo.glamour_level) || 0)}`}
      >
        <div className="intro_content">
          <NavBar
            title={<NavTab navigate={navigate} type={type} onClick={onChange} />}
            style={{
              paddingTop: barHeight
            }}
            other={
              <div
                className="detail_icon"
                onClick={() => {
                  navigate(`/level_detail?type=${type}`)
                }}
              ></div>
            }
          />
          <div className="my_info_card">
            <div className="user_info" style={{ marginTop: `${45 - barHeight}px` }}>
              {nickname ? (
                <div>
                  <div className="title">{nickname}</div>
                  {isNew ? (
                    <div style={{ color: '#fff', opacity: 0.6 }}>未解锁</div>
                  ) : (
                    <div className="progress">
                      <div className="progress_data">
                        <span>{`${(type === 'vip' ? levelData.wealth : levelData.glamour) || 0}/${(type === 'vip' ? levelData.nextWealth : levelData.nextGlamour) || 0}`}</span>
                        <ProgressBar
                          percent={
                            +(
                              (type === 'vip' ? levelData.wealth : levelData.glamour) /
                              (type === 'vip' ? levelData.nextWealth : levelData.nextGlamour)
                            ) * 100
                          }
                          style={{
                            '--fill-color': 'linear-gradient(270deg, #FFF 0%, rgba(255, 255, 255, 0.00) 97%)',
                            '--track-color': 'rgba(255,255,255,0.2)',
                            padding: '2px 0 4px 0'
                          }}
                        />
                        <span>
                          距Lv{levelData.nextLevel}还差{levelData.diff}成长值
                        </span>
                      </div>
                      {type === 'vip' || (userInfo.is_union_member && type === 'glamour') ? (
                        <div
                          className="clear_btn"
                          onClick={() => {
                            setVisible(true)
                            setTargetDate(Date.now() + 5000)
                          }}
                        >
                          <span>清除{type === 'vip' ? '财富' : '魅力'}等级</span>
                        </div>
                      ) : null}
                    </div>
                  )}
                </div>
              ) : null}
            </div>
            {/* <div className="intro_txt">{data[type].tips}</div> */}
          </div>
          <div className="box send_data">
            <div className="title">
              <div className="icon"></div>
              <div>{type === 'vip' ? '财富' : '魅力'}等级特权</div>
            </div>
            <div className="box_content">
              {levelData.reward.map((item, idx) => (
                <div key={idx} className="item">
                  <div className="box_i">
                    <div className={`icon ${+levelData.nextLevel - 1 < item.level ? 'disabled' : ''}`}>
                      <img src={item.show_img} alt="" />
                    </div>
                    {+levelData.nextLevel - 1 < item.level && <div className="lock"></div>}
                  </div>
                  <div className="name">{item.name}</div>
                  <div className="lv">Lv{item.level}解锁</div>
                </div>
              ))}
            </div>
          </div>

          <AmeModal
            onCancel={() => setVisible(false)}
            visible={visible}
            title={`是否花费10${window.baseConfig.coin_name}清除该账号${type === 'vip' ? '财富' : '魅力'}等级？`}
            disabledConfirm={Boolean(Math.round(countdown / 1000))}
            confirmText={Math.round(countdown / 1000) ? `确定（${Math.round(countdown / 1000)}）` : '确定'}
            onConfirm={clearLevel}
          >
            <div className="danger_txt">注意：该行为不可逆，清除后无法恢复原{type === 'vip' ? '财富' : '魅力'}值</div>
          </AmeModal>
        </div>
      </div>
    </div>
  )
}

export default LevelIntroduction
